import { HttpException, HttpStatus, Injectable, UseFilters } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { isNil, isEmpty } from 'ramda'
import { throwHttp } from 'src/utlis'
import { Like, Repository } from 'typeorm'
import { IdDto } from '../common/dto/dto'
import { HttpExceptionFilter } from '../http-exception.filter'
import { ArticleTagDto, CreateTagDto, UpdateCategoryTagDto } from './dto/article_tag.dto'
import { TagResult, Tags } from './entities/article_tag.entity'

@Injectable()
export class ArticleTagService {
  constructor(@InjectRepository(Tags) private articleTagsRepository: Repository<Tags>) {}
  // 获取标签
  @UseFilters(new HttpExceptionFilter())
  async getArticleTag(params: ArticleTagDto): Promise<TagResult> {
    try {
      const pageSize = Number(params.pageSize) || 10
      let { pageNum = 0 } = params
      if (pageNum !== 0) {
        pageNum -= 1
      }
      const [data, total] = await this.articleTagsRepository.findAndCount({
        where: {
          name: Like(`%${params.name ?? ''}%`),
        },
        skip: pageNum * pageSize,
        take: pageSize,
        cache: true,
      })
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum * pageSize + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 获取标签详情
  @UseFilters(new HttpExceptionFilter())
  async getTagInfo({ id }: IdDto): Promise<{ data: Tags }> {
    try {
      const data = await this.articleTagsRepository.findOne({
        where: { id },
      })
      if (isNil(data) || isEmpty(data)) {
        throwHttp( '标签不存在，请检查id是否正确')
      }
      return {
        data,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 创建标签
  @UseFilters(new HttpExceptionFilter())
  async createTag({ name }: CreateTagDto) {
    try {
      const data = await this.articleTagsRepository.findOne({
        where: { name },
      })
      if (!isNil(data)) {
        throwHttp('标签已存在')
      }
      const tags = new Tags()
      tags.name = name
      const result = await this.articleTagsRepository.manager.save(tags)
      return result
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 更新标签
  @UseFilters(new HttpExceptionFilter())
  async updateTag({ id, name }: UpdateCategoryTagDto): Promise<string> {
    try {
      await this.getTagInfo({ id })
      const { affected } = await this.articleTagsRepository.createQueryBuilder().update('article_tag').set({ name }).where('id = :id', { id }).execute()
      if (affected) {
        return '更新成功'
      }
      throwHttp('更新标签失败')
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 删除分类
  @UseFilters(new HttpExceptionFilter())
  async delTag({ id }: IdDto) {
    try {
      const { data } = await this.getTagInfo({ id })
      const tag = await this.articleTagsRepository.remove(data)
      return `删除成功`
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
